using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using MonoTouch.Foundation;
using MonoTouch.UIKit;
using CoachingOrganizer.iOS.Controllers;
using CoachingOrganizer.Logic.Models.Common;
using CoachingOrganizer.iOS.Decorators;
using CoachingOrganizer.iOS.Helpers;

namespace CoachingOrganizer.iOS.DataSources
{
    public class GoalsDataSource : UITableViewSource
    {
        public const string CellIdentifer = "GoalCell";

        private readonly UITableView _view;
        private readonly PeriodDetailsViewController _controller;
        private readonly PeriodModel _model;
        private readonly SimpleTableDataSourceDecorator<GoalViewController, GoalModel> _tableCellsSource;

        public GoalsDataSource(UITableView view, PeriodDetailsViewController controller, PeriodModel model)
        {
            _view = view;
            _controller = controller;
            _model = model;
            _tableCellsSource = new SimpleTableDataSourceDecorator<GoalViewController, GoalModel>(CellIdentifer, _view, _controller, p => _model.Goals.ElementAtOrDefault(p.Row), m => new GoalViewController(m));
            model.GoalsChanged += Model_GoalsChanged;
            model.GoalsCollectionChanged += Model_GoalsCollectionChanged;
        }

        public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath)
        {
            return _tableCellsSource.GetCell(indexPath);
        }

        public override int RowsInSection(UITableView tableview, int section)
        {
            return UIHelper.GetCollectionItemsCount(_model.Goals);
        }

        private void Model_GoalsChanged(object sender, EventArgs e)
        {
            _tableCellsSource.ProceedCollectionReplaced();
        }

        private void Model_GoalsCollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            _tableCellsSource.ProceedCollectionChanged(e);
        }
    }
}